import axios from 'axios'
import store from '@/store'
import storage from 'store'
import notification from 'ant-design-vue/es/notification'
import { VueAxios } from './axios'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { encryptBase64, encryptWithAes, generateAesKey } from '@/utils/crypto'
import { encrypt } from '@/utils/jsencrypt'

const encryptHeader = 'encrypt-key'

// 创建 axios 实例
const request = axios.create({
  // TODO API 请求的默认前缀
  //baseURL: process.env.VUE_APP_API_BASE_URL,
  baseURL: 'http://localhost:8080',
  timeout: 8000 // 请求超时时间
})

// 异常拦截处理器
const errorHandler = (error) => {
  if (error.response) {
    const data = error.response.data
    // 从 localstorage 获取 token
    if (error.response.status === 403) {
      notification.error({
        message: '禁止访问',
        description: data.message
      })
    }
    if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
      notification.error({
        message: '未经授权',
        description: '授权验证失败'
      })
      /*if (token) {
        store.dispatch('Logout').then(() => {
          setTimeout(() => {
            window.location.reload()
          }, 1500)
        })
      }*/
    }
  }
  return Promise.reject(error)
}

// 请求拦截器
request.interceptors.request.use(config => {
  const token = storage.get(ACCESS_TOKEN)
  // 如果 token 存在
  // 让每个请求携带自定义 token 请根据实际情况自行修改
  if (token) {
    config.headers[ACCESS_TOKEN] = 'Bearer ' + token
  }
  const isEncrypt = config.headers?.isEncrypt
  if (isEncrypt && (config.method === 'post' || config.method === 'put')) {
    // 生成一个 AES 密钥
    const aesKey = generateAesKey()
    config.headers[encryptHeader] = encrypt(encryptBase64(aesKey))
    config.data = typeof config.data === 'object' ?
      encryptWithAes(JSON.stringify(config.data), aesKey) :
      encryptWithAes(config.data, aesKey)
  }
  return config
}, errorHandler)

// 响应拦截器
request.interceptors.response.use((response) => {
  // 当响应状态码不等于200时
  if (response.data.code === 200) {
    return response.data
  }
  if (response.data.code === 401) {
    notification.error({
      message: '权限不足 无法访问 请重新登录',
      description: response.data.msg
    })
    store.dispatch('Logout').then(() => {
      setTimeout(() => {
        window.location.reload()
      }, 1500)
    })
    return Promise.reject(response.data)
  }
  if (response.data.code !== 200) {
    notification.error({
      message: '错误',
      description: response.data.msg
    })
    return Promise.reject(response.data)
  }
}, errorHandler)

const installer = {
  vm: {},
  install(Vue) {
    Vue.use(VueAxios, request)
  }
}

export default request

export {
  installer as VueAxios,
  request as axios
}
